package com.ssii.www.myproject.web.controller;

import com.ssii.www.myproject.common.util.AjaxResult;
import com.ssii.www.myproject.common.util.LogUtils;
import com.ssii.www.myproject.common.util.UserContext;
import com.ssii.www.myproject.domain.User;
import com.ssii.www.myproject.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
public class LoginController {
  private final static Logger logger = LogUtils.getLogger();

  @RequestMapping("/login")
  @ResponseBody
  public AjaxResult login(String username,String password){
    AjaxResult ajaxResult = null;

    //获取当前用户
    Subject currentUser = SecurityUtils.getSubject();
    //判断这个人是否认证 //这里有个问题就不判断了，直接封装
    //if(!currentUser.isAuthenticated()){
    //没有就认证
    //将用户名和密码封装成一个token对象
    UsernamePasswordToken token = new UsernamePasswordToken(username,password);
    User user = null;
    try {

      //调用当前用户的登陆方法
      currentUser.login(token);
      ajaxResult = new AjaxResult();
      //要将用户信息存入到session当中
      //首先获得当前用户 Object类型强转
       user = (User) currentUser.getPrincipal();
      //存入session
      //使用自定义的封装类UserContext
      UserContext.setUser(user);
    } catch (UnknownAccountException e) {
      logger.error("",e);
      ajaxResult = new AjaxResult("用户名不存在",-100);
    }catch (IncorrectCredentialsException e){
      logger.error("",e);
      ajaxResult = new AjaxResult("密码错误",-101);
    }catch (AuthenticationException e){
      logger.error("认证信息错误",e);
      ajaxResult = new AjaxResult("网络异常",-102);
    }
    //}
    if(user!=null&&user.getForbidden()==1){
      ajaxResult = new AjaxResult("用户被禁用",-103);
      logger.error("用户被禁用-----"+user.getName()+"---时间----"+new Date());
    }
    return ajaxResult;
  }
}
